<template>
    <div class="app-view">
        <transition name="fade-transform" mode="out-in">
            <vxe-grid v-show="!showCreate"
                      id="xGrid"
                      :loading="loading"
                      ref="xGrid"
                      border
                      resizable
                      show-overflow
                      keep-source
                      highlight-hover-row
                      :height="tableH"
                      align="center"
                      :print-config="{}"
                      :import-config="{}"
                      :export-config="{}"
                      :custom-config="{storage: true}"
                      :toolbar-config="tableToolbar"
                      :edit-config="editConfig"
                      :edit-rules="formRules"
                      :columns="tableColumn"
                      :seq-config="{startIndex: (tablePage.currentPage - 1) * tablePage.pageSize}"
                      :pager-config="tablePage"
                      :data="tableData"
                      @page-change="handlePageChange"
                      @edit-closed="editClosed">
                <template v-slot:toolbar_buttons>
                    <div class="tableToolbar">
                        <div style="min-width: 70px; margin-block: auto;" class="tableToolbarText">光路名称：</div>
                        <el-input v-model="searchName" size="mini" placeholder="请输入光路名称查询" clearable class="tableToolbarTextL" style="width: 230px;" @change="getData(0)" />
                        <el-button type="primary" size="mini" class="tableToolbarTextL" @click="getData(0)">查询</el-button>
                        <el-button type="primary" size="mini" @click="create">新增</el-button>

                    </div>
                </template>

                <template #operate="{ row }">
                    <el-link type="primary" class="elLinkBTN" @click="edit(row)">编辑</el-link>
                    <el-link type="danger" class="elLinkBTN" @click="deleteDe(row)">删除</el-link>
                </template>
            </vxe-grid>
        </transition>

        <transition name="fade-transform" mode="out-in">
            <div v-show="showCreate">
                <el-page-header @back="goBack">
                    <div slot="content">
                        {{ formTitle }}
                        <div style="position: absolute;right: 52px;top: 15px;">
                            <vxe-button status="primary" size="small" content="保存" @click="save" />
                        </div>
                    </div>
                </el-page-header>
                <div class="elscrollbar_gg" :style="{'height': (tableH - 44) + 'px'}">
                    <el-scrollbar style="height:100%;margin-top:30px">
                        <div style="max-width: 900px;margin: 20px auto;">
                            <vxe-form ref="myform" :loading="formLoading" :data="formInfo" title-width="90" :items="formItems" :rules="formRules">
                                <template #customer="{ data }">
                                    <vxe-input v-model="searchCustomer" readonly placeholder="请选择" />
                                </template>

                            </vxe-form>
                        </div>
                    </el-scrollbar>
                </div>
            </div>
        </transition>
    </div>
</template>
<script>
    import baseAPI from '../../request/Base/BaseAPI.js';
    import userjson from '../../common/json/userOption.js';
    export default {
        data() {
            return {
                userjson,
                loading: false,
                searchName: '',
                titleOption: [],
                titleLevelOption: [],
                tableH: window.innerHeight - topBarHeight - 80,
                customers: [],
                searchCustomer: null,
                tableColumn: [
                    { type: 'seq', title: '序号', width: 60, fixed: 'left' },
                    { field: 'customerName', title: '光路名称', fixed: 'left', minWidth: 200 },
                    { field: 'createTime', title: '创建时间', width: 120, formatter: ({ row }) => { return this.toDate(row.createTime) } },
                { field: 'createUID', title: '创建人', width: 130, formatter: ({ row }) => { return this.getUser(row.createUID) } },
                    { title: '操作', fixed: 'right', width: 160, slots: { default: 'operate' } }
                ],
                editConfig: {
                    enabled: true,
                    trigger: 'click',
                    mode: 'row',
                    showStatus: true
                },
                tableToolbar: {
                    refresh: {
                        query: () => this.getData()
                    },
                    import: false,
                    export: false,
                    print: false,
                    custom: true,
                    slots: {
                        buttons: 'toolbar_buttons'
                    }
                },
                tablePage: {
                    total: 0,
                    currentPage: 1,
                    pageSize: 50,
                    align: 'right',
                    pageSizes: [50, 80],
                    layouts: ['Sizes', 'PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'FullJump', 'Total'],
                    perfect: true
                },
                tableData: [],

                showCreate: false,
                formLoading: false,
                formTitle: '',
                formInfo: {},
                formItems: [
                    { field: 'customerName', title: '光路名称', span: 24, itemRender: { name: '$input', props: { placeholder: '请填写光路名称' } } },

                ],
                formRules: {
                    customerName: [{ required: true, message: '请填写光路名' }],
                },
                uploadUrl: '',
                fileList: [],
                formInfoID: null,
                isAdd: false,
                signFrontInfo: '',
            };
        },
        mounted() {
            this.getData(0);
            var _this = this;
            window.onresize = () => {
                return (() => {
                    _this.tableH = window.innerHeight - 80 - 80;
                })();
            };
        },
        beforeDestroy() {
            window.onresize = null;
        },
        methods: {
            getData(type) { // 获取光路列表
                if (type === 0) {
                    this.tablePage.currentPage = 1;
                }
                this.loading = true;
                var whereStr = "isDelete = 0 ";

                if (!!this.searchName) {
                    whereStr += " and customerName like '%" + this.searchName.trim() + "%' ";
                }
                baseAPI.getCustomerList({
                    pageIndex: this.tablePage.currentPage - 1,
                    pageSize: this.tablePage.pageSize,
                    where: whereStr,
                }).then(res => {
                    this.tableData = res.result;
                    this.tablePage.total = res.recordCount;
                    this.loading = false;
                }).catch(() => {
                    this.loading = false;
                });
            },
            handlePageChange({ currentPage, pageSize }) {
                this.tablePage.currentPage = currentPage;
                this.tablePage.pageSize = pageSize;
                this.getData();
            },
            editClosed({ row, rowIndex }) {
                this.$refs.xGrid.validate().then(suc => {
                    if (!suc) {
                        baseAPI.update(row).then(res => {
                            this.$message({ type: 'success', message: '修改成功' });
                            this.getData();
                        }).catch(err => { });
                    }
                }).catch(err => { });
            },

            create() {
                this.formTitle = '新增光路';
                this.fileList = [];
                this.titleLevelOption = [];
                this.signFrontInfo = '';
                this.formInfo = {
                    customerName: '',
                    isDelete: false,
                };
                this.showCreate = true;
            },
            edit(row) {
                this.formTitle = '编辑光路信息';
                this.showCreate = true;
                this.formLoading = true;
                this.fileList = [];
                this.titleLevelOption = [];
                this.signFrontInfo = '';
                baseAPI.getCustomerByID(row.customerID).then(res => {
                    this.formInfo = res;
                    //if (!!res.signFront) {
                    //    this.signFrontInfo = res.signFront;
                    //    this.fileList.push({ name: res.signFront + '.ttf' })
                    //}
                    //this.getTitle();
                    this.formLoading = false;
                }).catch(() => {
                    this.formLoading = false;
                });
            },
            deleteDe(row) {
                this.$confirm(`是否删除光路 ${row.customerName}`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.loading = true;
                    baseAPI.deleteCustomer(row.customerID).then(res => {
                        if (!res) {
                            this.$message({ type: 'warning', message: '删除失败!' });
                        }
                        this.$message({ type: 'success', message: '删除成功!' });
                        this.getData(0);
                    });
                }).catch(() => {
                    this.loading = false;
                });
            },
            save() {
                this.$refs.myform.validate().then(suc => {
                    if (!suc) {

                        this.formInfo.customerID ? this.isAdd = true : this.isAdd = false;
                        this.formLoading = true;
                        baseAPI[this.formInfo.customerID ? 'updateCustomer' : 'createCustomer'](this.formInfo).then(res => {
                            if (res) {
                                if (this.fileList.length > 0 && this.fileList[0].status == 'ready') {
                                    //if (this.fileList.length > 0 && this.signFrontInfo != this.formInfo.signFront) {
                                    this.formInfoID = res.customerID;
                                    this.$refs.UpLoad.submit();
                                } else {
                                    this.$message({ type: 'success', message: this.isAdd ? '修改成功' : '创建成功' });
                                    this.formLoading = false;
                                    this.showCreate = false;
                                    this.getData(0);
                                }
                            } else {
                                this.$message({ type: 'warning', message: this.isAdd ? '修改失败' : '创建失败' });
                                this.formLoading = false;
                                this.showCreate = false;
                                this.getData(0);
                            }

                        }).catch(err => {
                            this.formLoading = false;
                        });
                    }
                }).catch(() => { });
            },
            goBack() {
                this.showCreate = false;
                this.$refs.myform.reset();
                this.getData(0);
            },

            format(ops, op, hasops) {
                var val = null;
                if (hasops) {
                    var options = ops.map(e => {
                        return e.options;
                    }).flat().valueOf();
                    val = options.find(e => e.value === op);
                } else {
                    val = ops.find(e => e.value === op);
                }
                return val ? val.label : '';
            },
            toDate(date) {
                return date ? moment(date).format("YYYY-MM-DD") : "";
            },
            getUser(date) {
                return date ? JSON.parse(sessionStorage.getItem('userList')).find(x => x.userid === date).realname : '';
            },
        },
        template: "#template"
    };
</script>
